package com.example.dell.intelligentagriculture.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.example.dell.intelligentagriculture.ControlActivity;
import com.example.dell.intelligentagriculture.R;
import com.example.dell.intelligentagriculture.Service.WebService;
import com.example.dell.intelligentagriculture.utils.Agriculture;
import com.example.dell.intelligentagriculture.utils.HttpUtil;
import com.example.dell.intelligentagriculture.utils.MyApp;
import com.example.dell.intelligentagriculture.utils.SlidePhoto;

import org.json.JSONException;
import org.json.JSONObject;



public class HomeFragment extends Fragment implements View.OnClickListener {
    public static final int MSG_CHANGE_AUTO_BIND = 100;
    public static final int MSG_SERVER_DATA = 101;
    private View view;
    private int[] imgArray; //存放viewpager的背景图片（三张轮播图）
    private ImageView[] bandimgArray;// 存放viewpager中的imageview
    private ImageView[] tips;//存放小圆点（小圆点控件imageview）
    private LinearLayout viewGroup;
    private TextView co2txtValue, guangtxtValue, turangWenValue, turangShiValue, kongqiWenValue, kongqiShiValue;
    private TextView co2SetValue, guangSetValue, turangWenSetValue, turangShiSetValue, kongqiWenSetValue, kongqiShiSetValue;
    private ImageView yujing1, yujing2, yujing3, yujing4;
    private int minCo2, maxC02, minGuang, maxGuang, minTuShi, maxTuShi, minTuWen, maxTuWen, minKongShi, maxKongShi, minKongWen, maxKongWen;
    private ViewPager viewPager;
    private RelativeLayout co2, guangzhao, turang, kongqi;
    private HttpUtil httpUtil;
    private SharedPreferences sp;
    private MyApp myApp;
    private MyReceiver myReceiver;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case MSG_CHANGE_AUTO_BIND:
                    //获取当前图片的item的索引值
                    int currentItem = viewPager.getCurrentItem();
                    viewPager.setCurrentItem(currentItem + 1);
                    //递归
                    handler.sendEmptyMessageDelayed(MSG_CHANGE_AUTO_BIND, 5000);
                    break;
            }

        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_home, null);
            initView();
            ImageView[] tips = new SlidePhoto(viewGroup, viewPager, getActivity()).initBandRes();
            if (tips.length > 0) {
                //延时多长时间后执行发送  sendEmptyMessageDelaye默认运行在子线程中
                handler.sendEmptyMessage(MSG_CHANGE_AUTO_BIND);
            }

        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        return view;
    }

    /**
     * 改变预警图标
     *
     * @param curr
     * @param max
     * @param min
     * @param view
     * @return
     */
    private boolean changeYujingImg(int curr, int max, int min, View view) {
        if (curr <= max && curr >= min) {
            view.setBackgroundResource(R.mipmap.p1);
            return true;
        } else if (curr < min) {
            view.setBackgroundResource(R.mipmap.p2);
            return false;
        } else {
            view.setBackgroundResource(R.mipmap.p3);
            return false;
        }
    }


    /**
     * 初始化控件
     */
    private void initView() {
        initReceiver();
        sp = getActivity().getSharedPreferences("maxInfo", Context.MODE_PRIVATE);
        myApp = (MyApp) getActivity().getApplication();
        httpUtil = new HttpUtil(sp);
        viewGroup = view.findViewById(R.id.ll_viewGroup);
        viewPager = view.findViewById(R.id.viewPager);
        co2 = view.findViewById(R.id.co2);
        guangzhao = view.findViewById(R.id.guangzhao);
        turang = view.findViewById(R.id.turang);
        kongqi = view.findViewById(R.id.kongqi);

        co2txtValue = view.findViewById(R.id.co2txtValue);
        guangtxtValue = view.findViewById(R.id.guangtxtValue);
        turangWenValue = view.findViewById(R.id.turangWenValue);
        turangShiValue = view.findViewById(R.id.turangShiValue);
        kongqiWenValue = view.findViewById(R.id.kongqiWenValue);
        kongqiShiValue = view.findViewById(R.id.kongqiShiValue);

        co2SetValue = view.findViewById(R.id.co2SetValue);
        guangSetValue = view.findViewById(R.id.guangSetValue);
        turangWenSetValue = view.findViewById(R.id.turangWenSetValue);
        turangShiSetValue = view.findViewById(R.id.turangShiSetValue);
        kongqiWenSetValue = view.findViewById(R.id.kongqiWenSetValue);
        kongqiShiSetValue = view.findViewById(R.id.kongqiShiSetValue);

        yujing1 = view.findViewById(R.id.yujing1);
        yujing2 = view.findViewById(R.id.yujing2);
        yujing3 = view.findViewById(R.id.yujing3);
        yujing4 = view.findViewById(R.id.yujing4);

        co2.setOnClickListener(this);
        guangzhao.setOnClickListener(this);
        turang.setOnClickListener(this);
        kongqi.setOnClickListener(this);
        makeSetValue();
    }

    /**
     * 给设定值赋值
     */
    private void makeSetValue() {
        String extreme = sp.getString("extreme", "");
        try {
            JSONObject json = new JSONObject(extreme);
            minCo2 = json.getInt("minCo2");
            maxC02 = json.getInt("maxCo2");
            minGuang = json.getInt("minLight");
            maxGuang = json.getInt("maxLight");
            minTuShi = json.getInt("minSoilHumidity");
            maxTuShi = json.getInt("maxSoilHumidity");
            minTuWen = json.getInt("minSoilTemperature");
            maxTuWen = json.getInt("maxSoilTemperature");
            minKongShi = json.getInt("minAirHumidity");
            maxKongShi = json.getInt("maxAirHumidity");
            minKongWen = json.getInt("minAirTemperature");
            maxKongWen = json.getInt("maxAirTemperature");
            //co2SetValue, guangSetValue, turangWenSetValue, turangShiSetValue, kongqiWenSetValue, kongqiShiSetValue
            co2SetValue.setText(minCo2 + "~~" + maxC02);
            guangSetValue.setText(minGuang + "~~" + maxGuang);
            turangWenSetValue.setText(minTuWen + "~~" + maxTuWen);
            turangShiSetValue.setText(minTuShi + "~~" + maxTuShi);
            kongqiWenSetValue.setText(minKongWen + "~~" + maxKongWen);
            kongqiShiSetValue.setText(minKongShi + "~~" + maxKongShi);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(), ControlActivity.class);

        switch (v.getId()) {
            case R.id.co2:
                intent.putExtra("item", 1);
                break;
            case R.id.guangzhao:
                intent.putExtra("item", 2);
                break;
            case R.id.turang:
                intent.putExtra("item", 3);
                break;
            case R.id.kongqi:
                intent.putExtra("item", 4);
                break;
        }
        startActivity(intent);
    }

    /**
     * 广播接收者
     */
    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WebService.ACTION.equals(action)) {
                Agriculture agriculture = (Agriculture) intent.getSerializableExtra("mySensor");
                int co2 = agriculture.getCo2();
                int light = agriculture.getLight();
                int soilTemperature = agriculture.getSoilTemperature();
                int soilHumidity = agriculture.getSoilHumidity();
                int airTemperature = agriculture.getAirTemperature();
                int airHumidity = agriculture.getAirHumidity();
                co2txtValue.setText(co2 + "");
                guangtxtValue.setText(light + "");
                turangWenValue.setText(soilTemperature + "");
                turangShiValue.setText(soilHumidity + "");
                kongqiWenValue.setText(airTemperature + "");
                kongqiShiValue.setText(airHumidity + "");

                if (co2 <= maxC02 && co2 >= minCo2) {
                    yujing1.setImageResource(R.mipmap.p1);
                } else if (co2 > maxC02) {
                    yujing1.setImageResource(R.mipmap.p3);
                } else {
                    yujing1.setImageResource(R.mipmap.p2);
                }

                if (light <= maxGuang && light >= minGuang) {
                    yujing2.setImageResource(R.mipmap.p1);
                } else if (light > maxGuang) {
                    yujing2.setImageResource(R.mipmap.p3);
                } else {
                    yujing2.setImageResource(R.mipmap.p2);
                }

                if (soilTemperature <= maxTuWen && soilTemperature >= minTuWen && soilHumidity <= maxTuShi && soilHumidity >= minTuShi) {
                    yujing3.setImageResource(R.mipmap.p1);
                } else {
                    yujing3.setImageResource(R.mipmap.p3);
                }

                if (airTemperature <= maxKongWen && airTemperature >= minKongWen && airHumidity <= maxKongShi && airHumidity >= minKongShi) {
                    yujing4.setImageResource(R.mipmap.p1);
                } else {
                    yujing4.setImageResource(R.mipmap.p3);
                }

            }
        }
    }

    /**
     * 注册广播接收者
     */
    private void initReceiver() {
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WebService.ACTION);
        getActivity().registerReceiver(myReceiver, intentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(myReceiver);
    }
}